#  StormMUD - A multiplayer combat game - http://stormmud.david-c-brown.com
#  Copyright (C) 2009, 2010 - David C Brown & Mark Richardson
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# StormMUD imports
from smError import UnrecoverableError, UnspecifiedErrorExit
from smDefines import FILE, CONSOLE

# Standard Python lib imports
import sys

from ConfigParser import ConfigParser

# Global Config object
GameConfig = None

#==================================================
# Class Config
#
# All configurations read from the config file
# are read into this configurations object
# as GameConfig.  It is loaded at start up
#==================================================
class Config:
    """class Config:  This is the class object for the games configurations.
       There is only one of these for the game.  It holds all global configuration
       data for the game. It doesn't contain any game data"""

    # Initialize
    def __init__( self ):
        """Initialize the configuration object"""

        self.ServerName                = ""
        self.port                      = 0
        self.MaxPlayers                = 0
        self.Money                     = {}

        self.Logfile                   = ""
        self.LogInfo                   = {}
        self.LogDebug                  = {}
        self.LogWarn                   = {}
        self.LogError                  = {}

        # Databases
        self.PlayerDB                  = ""
        self.WorldMap                  = ""


        # Load the config file
        self.LoadConfig()


    def LoadConfig( self ):
        """Config -> LoadConfig(): This loads the configuration data into the
           configuration class object from the config file."""

        cfg = "StormMUD.cfg"

        # Load the config file
        config = ConfigParser()
        try:
            config.readfp(open(cfg))
        except IOError as (errno, strerror):
            print "I/O error opening {0}: {1}".format(cfg, strerror) 
            UnrecoverableError()
        except:
            UnrecoverableError()
            raise

        # Apply the settings to the GameConfig
        try:
            # [StormMUD] Section of the config file
            self.ServerName         =      config.get("StormMUD", 'ServerName')
            self.port               = int( config.get("StormMUD", 'Port') )
            self.MaxPlayers         = int( config.get("StormMUD", 'MaxPlayers') )
            self.PlayerDB           =      config.get("StormMUD", 'PlayerDB')
            self.MapDirectory       =      config.get("StormMUD", 'MapDirectory')
            self.FirstMap           =      config.get("StormMUD", "FirstMap")
            self.Money[1]           =      config.get("StormMUD", 'Cash1')  # Cash# is currency names
            self.Money[2]           =      config.get("StormMUD", 'Cash2')  # At some point, need to assign them
            self.Money[3]           =      config.get("StormMUD", 'Cash3')  # in a better place than the global config (bank module?)
            self.Money[4]           =      config.get("StormMUD", 'Cash4')
            self.Money[5]           =      config.get("StormMUD", 'Cash5')

            # [StormMUD Logging] Section of the config file
            self.Logfile            =      config.get("StormMUD Logging", 'Logfile')
            logStr                  =      config.get("StormMUD Logging", 'INFO')
            self.LogInfo[FILE]      =      self.GetLoggingPref(FILE, logStr)
            self.LogInfo[CONSOLE]   =      self.GetLoggingPref(CONSOLE, logStr)
            logStr                  =      config.get("StormMUD Logging", 'DEBUG')
            self.LogDebug[FILE]     =      self.GetLoggingPref(FILE, logStr)
            self.LogDebug[CONSOLE]  =      self.GetLoggingPref(CONSOLE, logStr)
            logStr                  =      config.get("StormMUD Logging", 'WARN')
            self.LogWarn[FILE]      =      self.GetLoggingPref(FILE, logStr)
            self.LogWarn[CONSOLE]   =      self.GetLoggingPref(CONSOLE, logStr)
            logStr                  =      config.get("StormMUD Logging", 'ERROR')
            self.LogError[FILE]     =      self.GetLoggingPref(FILE, logStr)
            self.LogError[CONSOLE]  =      self.GetLoggingPref(CONSOLE, logStr)



        except ConfigParser.NoSectionError:
            print "Error: StormMUD section missing from %s" % cfg 
            UnrecoverableError()

        except ConfigParser.NoSectionError:
            print "Error: StormMUD section missing from %s" % cfg 
            UnrecoverableError()

        except ConfigParser.NoOptionError as (strerror):
            print "Config file error: {0}".format(strerror) 
            UnrecoverableError()

        except ConfigParser.ParsingError as (strerror):
            print "Config file error: {0}".format(strerror) 
            UnrecoverableError()

        except:
            UnspecifiedErrorExit()

    #=========================================
    # GetLoggingPref()
    #=========================================
    def GetLoggingPref(self, LogType, configStr):
        """
        GetLoggingPref() returns a boolean of named
        log location exists. Currently FILE and CONSOLE
        are supported.
        """
        cfg = configStr.lower()

        if LogType == CONSOLE:
            if "console" in cfg:
                return True
            else:
                False
        else:
            if "file" in cfg:
                return True
            else:
                return False


